import { mapActions } from 'vuex';
import authModal from '@/utils/mixins/modal/auth';

export default {
  mixins: [authModal],

  data() {
    return {
      // form
      form: this.$form.createForm(this, { first: true }),

      // state
      state: {
        time: 60,
        loginBtn: false,
        // login type: 0 email, 1 username, 2 telephone
        loginType: 0,
        smsSendBtn: false
      }
    };
  },
  methods: {
    ...mapActions(['Login', 'Logout']),

    // submit
    handleSubmit(e) {
      e.preventDefault();
      const {
        form: { validateFields, getFieldsValue },
        state,
        Login
      } = this;

      state.loginBtn = true;

      const validateFieldsKey = ['email', 'password'];

      validateFields(validateFieldsKey, { force: true, first: true }, (err, values) => {
        if (!err) {
          const fields = getFieldsValue(validateFieldsKey);
          Login(fields)
            .then((res) => this.loginSuccess(res))
            .catch((err) => this.requestFailed(err))
            .finally(() => {
              state.loginBtn = false;
            });
        } else {
          state.loginBtn = false;
        }
      });
    },

    // success
    loginSuccess(res) {
      this.$router.push({ path: '/' })
        .then(() => {
          setTimeout(() => {
            this.authModal();
          }, 1000);
        });
    },

    // failed
    requestFailed(err) {
    }
  }
};
